import {
	isString
} from '@/utils/assist.js';

export function uploadFile(url, userToken, tempFilePath, loadingText, data) {

	return new Promise((resolve, reject) => {
		if (loadingText) {
			uni.showLoading({
				title: isString(loadingText) ? loadingText : '上传中',
				mask: true
			});
		}
		uni.uploadFile({
			url: url,
			filePath: tempFilePath,
			name: 'file',
			header: {
				'Authorization': userToken
			},
			formData: data,
			success: (res) => {
				let data = JSON.parse(res.data)
				//更新用户信息
				if (data.code == 500) {
					uni.showToast({
						icon: 'error',
						title: data.msg,
						duration: 3000
					})
					// //跳转到首页
					// setTimeout(function() {
					// 	uni.reLaunch({
					// 		url: '/pages/index/index'
					// 	})
					// }, 3000)
				} else {
					return resolve(data)
				}
			},
			fail: (res) => {
				jumpIndex()
			},
			complete: (res) => {
				if (loadingText) {
					uni.hideLoading({
						noConflict: true
					});
				}
			}
		});
	});
}

function jumpIndex() {
	uni.showToast({
		icon: 'none',
		title: '数据加载失败！'
	})

	//跳转到首页
	setTimeout(function() {
		uni.reLaunch({
			url: '/pages/index/index'
		})
	}, 3000)
}